const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

/**
 * 获取所有系统设置
 */
exports.getAllSettings = async (req, res) => {
  try {
    const settings = await prisma.systemSetting.findMany();
    
    // 将设置按category分组
    const groupedSettings = settings.reduce((acc, setting) => {
      if (!acc[setting.category]) {
        acc[setting.category] = {};
      }
      acc[setting.category][setting.key] = {
        value: setting.value,
        description: setting.description
      };
      return acc;
    }, {});
    
    res.json({
      success: true,
      data: groupedSettings
    });
  } catch (error) {
    console.error('获取系统设置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取系统设置失败',
      error: error.message
    });
  }
};

/**
 * 获取特定类别的系统设置
 */
exports.getSettingsByCategory = async (req, res) => {
  const { category } = req.params;
  
  try {
    const settings = await prisma.systemSetting.findMany({
      where: { category }
    });
    
    // 转换为键值对格式
    const settingsMap = settings.reduce((acc, setting) => {
      acc[setting.key] = {
        value: setting.value,
        description: setting.description
      };
      return acc;
    }, {});
    
    res.json({
      success: true,
      data: settingsMap
    });
  } catch (error) {
    console.error(`获取${category}类别的系统设置失败:`, error);
    res.status(500).json({
      success: false,
      message: `获取${category}类别的系统设置失败`,
      error: error.message
    });
  }
};

/**
 * 更新系统设置
 */
exports.updateSettings = async (req, res) => {
  const { category } = req.params;
  const settings = req.body;
  
  if (!settings || typeof settings !== 'object') {
    return res.status(400).json({
      success: false,
      message: '无效的设置数据'
    });
  }
  
  try {
    // 使用事务确保更新的原子性
    const result = await prisma.$transaction(async (tx) => {
      const operations = [];
      
      for (const [key, data] of Object.entries(settings)) {
        const { value, description } = typeof data === 'object' ? data : { value: data, description: null };
        
        // 使用upsert确保不存在时创建，存在时更新
        operations.push(
          tx.systemSetting.upsert({
            where: {
              category_key: {
                category,
                key
              }
            },
            update: {
              value: String(value),
              description
            },
            create: {
              category,
              key,
              value: String(value),
              description,
              updatedAt: new Date()
            }
          })
        );
      }
      
      return await Promise.all(operations);
    });
    
    res.json({
      success: true,
      message: '系统设置更新成功',
      data: result.length
    });
  } catch (error) {
    console.error('更新系统设置失败:', error);
    res.status(500).json({
      success: false,
      message: '更新系统设置失败',
      error: error.message
    });
  }
};

/**
 * 删除系统设置
 */
exports.deleteSettings = async (req, res) => {
  const { category } = req.params;
  const { keys } = req.body;
  
  if (!keys || !Array.isArray(keys) || keys.length === 0) {
    return res.status(400).json({
      success: false,
      message: '请指定要删除的设置键'
    });
  }
  
  try {
    const result = await prisma.systemSetting.deleteMany({
      where: {
        category,
        key: { in: keys }
      }
    });
    
    res.json({
      success: true,
      message: '系统设置删除成功',
      data: result.count
    });
  } catch (error) {
    console.error('删除系统设置失败:', error);
    res.status(500).json({
      success: false,
      message: '删除系统设置失败',
      error: error.message
    });
  }
};

/**
 * 初始化默认系统设置
 */
exports.initDefaultSettings = async () => {
  try {
    // 基本设置
    await prisma.systemSetting.upsert({
      where: {
        category_key: {
          category: 'basic',
          key: 'systemName'
        }
      },
      update: {},
      create: {
        category: 'basic',
        key: 'systemName',
        value: '哈喽啤鲜生收银与库存管理系统',
        description: '系统名称',
        updatedAt: new Date()
      }
    });
    
    await prisma.systemSetting.upsert({
      where: {
        category_key: {
          category: 'basic',
          key: 'logoUrl'
        }
      },
      update: {},
      create: {
        category: 'basic',
        key: 'logoUrl',
        value: '/images/logo.png',
        description: '系统Logo URL',
        updatedAt: new Date()
      }
    });
    
    // 系统信息
    await prisma.systemSetting.upsert({
      where: {
        category_key: {
          category: 'system',
          key: 'version'
        }
      },
      update: {},
      create: {
        category: 'system',
        key: 'version',
        value: '1.0.0',
        description: '系统版本',
        updatedAt: new Date()
      }
    });
    
    await prisma.systemSetting.upsert({
      where: {
        category_key: {
          category: 'system',
          key: 'license'
        }
      },
      update: {},
      create: {
        category: 'system',
        key: 'license',
        value: 'MIT',
        description: '许可证信息',
        updatedAt: new Date()
      }
    });
    
    console.log('默认系统设置初始化成功');
  } catch (error) {
    console.error('初始化默认系统设置失败:', error);
  }
}; 